/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// my own modules
const sio = require('socket.io');
const moment = require('moment');
const config = require('./config/environment');
const logger = require('./services/logging').getLogger('app');

const http = require('http');
var names = [];


/*工具函数，应该封装成模块*/
var isNameAva = function (name) {
	var answer = true;
	for (var i = 0; i < names.length; i++) {
		if (names[i] == name) {
			answer = false;
			break;
		}
	};
	return answer;
};

function removeByValue(arr, val) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == val) {
			arr.splice(i, 1);
			break;
		}
	}
}

/******************************/

// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// create a new express server
var app = new express();

var server = http.createServer(app);

// // serve the files out of ./public as our main files
// app.use(express.static(__dirname + '/public/broadcast.html'));


app.get('/', function (req, res) {
	res.sendfile(__dirname + '/public/broadcast.html');
})

/*这里不是很理解*/


var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));


// start server on the specified port and binding host
server.listen(config.port, '0.0.0.0', function () {
	// print a message when the server starts listening
	logger.info("server listen on " + config.port);
});

var io = sio.listen(server);

io.sockets.on('connection', function (socket) {
	logger.info('setup socket conn.');
	socket.on('login', function () {
		socket.emit('login', names);
	});

	socket.on('newUserLogin', function (name) {
		if (isNameAva(name)) {
			logger.info('receive:' + name);
			names.push(name);
			logger.info('all users:' + names);
			socket.myName = name;

			io.sockets.emit('login', names);
			io.sockets.emit('newUserLogin', name);
			socket.emit('loginConfirmed');
		} else {
			socket.emit('repeatedName');
		}

	});

	socket.on('chat', function (msg) {
		let user = socket.myName;
		let date = moment().format('YYYY-MM-DD HH:mm:ss');
		var currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
		io.sockets.emit('chat', currentTime, msg, user);
	})

	socket.on('disconnect', function () {
		if (socket.myName && socket.myName != '') {
			io.sockets.emit('disconnect', socket.myName);
			logger.info(socket.myName + ' disconnect.');
			removeByValue(names, socket.myName);
			socket.emit('login', names);
			socket.myName = '';
		}
	});
	
	socket.on('logout', function () {
		if (socket.myName && socket.myName != '') {
			io.sockets.emit('disconnect', socket.myName);
			logger.info(socket.myName + ' logout.');
			removeByValue(names, socket.myName);
			socket.emit('login', names);
			socket.myName = '';
		}
	});
});